﻿using System.Collections.Generic;

namespace CommonUtils
{
    /// <summary>
    /// 线程安全Map ConcurrentDictionary可以访问，但可能取不到数据
    /// </summary>
    public class SafeMap<TKey, TValue>
    {
        private Dictionary<TKey, TValue> _map = new Dictionary<TKey, TValue>();

        private bool _lock = false;

        public KeyValuePair<TKey, TValue>[] GetPairs()
        {
            if (!_lock)
            {
                _lock = true;
                var pair = new List<KeyValuePair<TKey, TValue>>();
                pair.AddRange(_map);
                _lock = false;
                return pair.ToArray();
            }
            else
            {
                ThreadUtil.SleepSeconds(0.01);
                return GetPairs();
            }
        }

        public void Set(TKey key, TValue value)
        {
            if (!_lock)
            {
                _lock = true;
                _map[key] = value;
                _lock = false;
            }
            else
            {
                ThreadUtil.SleepSeconds(0.01);
                Set(key, value);
            }
        }

        public void Add(TKey key, TValue value = default)
        => Set(key, value);

        public bool Contains(TKey key)
        {
            if (!_lock)
            {
                _lock = true;
                var result = _map.ContainsKey(key);
                _lock = false;
                return result;
            }
            else
            {
                ThreadUtil.SleepSeconds(0.01);
                return Contains(key);
            }
        }

        public TValue Get(TKey key)
        {
            if (!_lock)
            {
                _lock = true;
                TValue value = default;
                if (_map.ContainsKey(key))
                    value = _map[key];
                _lock = false;
                return value;
            }
            else
            {
                ThreadUtil.SleepSeconds(0.01); ;
                return Get(key);
            }
        }
    }
}
